package com.tea.modules.java8.thread.atomic;

import com.google.common.collect.Lists;
import com.tea.modules.java8.thread.annotation.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 展示Atomic如何保证原子性
 * @author jaymin
 * @since 2022/2/19 21:45
 */
@ThreadSafe
@Slf4j
public class AtomicDemo {

    /**
     * 请求总数
     */
    public static final int clientTotal = 5000;
    /**
     * 同时并发线程数
     */
    public static final int threadTotal = 200;

    public static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("并发错误:", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        log.info("count:{}",count.get());
    }

    /**
     * 一个是先自增再get <br>
     * 一个是先get再自增 <br>
     */
    private static void add() {
        count.incrementAndGet();
        // count.getAndIncrement();
    }
}
